<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);

session_start();
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__ . '/../../model/UserModel.php';
use model\UserModel;

// 验证表单数据
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = '错误：仅支持POST请求';
}
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $realName = trim($_POST['realName'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email=trim($_POST['email']?? '');
    $role=(int)trim($_POST['role']?? '');

    $errors = [];

    // 用户名验证
    if (empty($username) || strlen($username) < 3 || strlen($username) > 10) {
        $errors[] = '用户名需为3-10位字符';
    }

    // 密码验证
    if (empty($password) || strlen($password) < 4 || strlen($password) > 16) {
        $errors[] = '密码需为4-16位字符';
    }

    // 真实姓名验证
    if (empty($realName)) {
        $errors[] = '真实姓名不能为空';
    }

    // 手机号验证
    if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
        $errors[] = '手机号格式不正确';
    }

    //邮箱验证
    if (!preg_match('/^[\w\-]+@[\w\-]+\.[a-z]{2,}$/i', $email)) {
        $errors[] = '邮箱格式不正确';
    }

    //权限验证
    if (!in_array($role, [0, 1])) {
        $errors[] = '权限设置错误';
    }

    if (empty($errors)) {
        $userModel = new UserModel();
        $data = [
            'username' => $username,
            'password' => $password,
            'name' => $realName,
            'phone' => $phone,
            'email' => $email,
            'role' => $role
        ];

        $result = $userModel->addUser($data);
        if ($result>0) {
            $_SESSION['success_message'] = '用户添加成功！';
        } else {
            $_SESSION['error_message'] = '用户添加失败，请重试。';
        }
    } else {
        $_SESSION['error_message'] = implode('；', $errors);
    }


// 重定向回用户列表页面
header('Location: Users.php');
exit;